# -*- coding: utf-8 -*-
"""
安装命令：pip install paramiko
"""


import paramiko


def update_authorized_keys(ip, port, user, key):
    print('port: {}'.format(port))
    private_key = paramiko.RSAKey.from_private_key_file(key)
    # 创建一个SSH客户端对象
    ssh = paramiko.SSHClient()
    # 设置访问策略
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        # 创建连接
        ssh.connect(ip, port, user, pkey=private_key)
        cmd = 'mkdir tmp_for_update_public_key && cd tmp_for_update_public_key && yum install -y git && git clone https://gitee.com/shihowcom/public_key.git && chmod 777 ./public_key/update_public_key.sh && ./public_key/update_public_key.sh'
        stdin, stdout, stderr = ssh.exec_command(cmd)
        print(stdout.read())
        print(stderr.read())
    except Exception:
        pass
    finally:
        ssh.close()
        print('-------------------------------')


def get_all_ip():
    ip = []
    with open('ip.txt', 'r') as f:
        for line in f.readlines():
            ip.append(line.strip())  # 去除每一行之后的换行符
    return ip


def main(key):
    ip_s = get_all_ip()
    print('to do ip(s):')
    print(ip_s)
    for ip in ip_s:
        print('to do ip: {}'.format(ip))
        update_authorized_keys(ip, 22, 'root', key)
        # update_authorized_keys(ip, 9922, 'root', key)


if __name__ == '__main__':
    PRIVATE_KEY = 'C:\Users\Administrator\.ssh\id_rsa'
    main(PRIVATE_KEY)
